package com.roc.util.converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.util.StrutsTypeConverter;

import com.roc.util.constant.Constant;

/**
 * @author RenPengFei
 *
 * 2011-11-23
 */
public class DateConverter extends StrutsTypeConverter {

	static Logger logger = LogManager.getLogger(DateConverter.class);
	
	/* (non-Javadoc)
	 * @see org.apache.struts2.util.StrutsTypeConverter#convertFromString(java.util.Map, java.lang.String[], java.lang.Class)
	 */
	@Override
	public Object convertFromString(Map context, String[] values, Class toClass) {
		if(values == null){
			return null;
		}
		Date result = null;
		SimpleDateFormat format = null;
		if(Constant.PAGE_FIELD_DATE_FORMAT.length() == values[0].length()){
			format = new SimpleDateFormat(Constant.PAGE_FIELD_DATE_FORMAT);
		}else{
			format = new SimpleDateFormat(Constant.PAGE_FIELD_DATE_TIME_FORMAT);
		}
		try {
			result = format.parse(values[0]);
		} catch (ParseException e) {
			logger.debug(e.getMessage(), e);
			throw new RuntimeException(e);
//			e.printStackTrace();
		}
		return result;
	}

	/* (non-Javadoc)
	 * @see org.apache.struts2.util.StrutsTypeConverter#convertToString(java.util.Map, java.lang.Object)
	 */
	@Override
	public String convertToString(Map context, Object o) {
		SimpleDateFormat format = new SimpleDateFormat(Constant.PAGE_FIELD_DATE_FORMAT);
		return format.format(o);
	}

}
